package com.ruoyi.project.system.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.project.system.domain.dto.*;
import com.ruoyi.project.system.mapper.SysPhoneMapper;
import com.ruoyi.project.system.service.ISysPhoneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import static com.ruoyi.project.system.domain.dto.AddressBook.getTelName;

@Service
public class SiyuPhoneServiceImpl implements ISysPhoneService {

    @Autowired
    private SysPhoneMapper spm;

    @Autowired
    private RedisCache redisCache;

    @Override
    public List<AddressBook> getAddressBook(Integer queryId) {
        List<AddressBook> addressBookList;
//        String abs = redisCache.getCacheObject("AB::" + queryId); // MGZ TODO 2025/4/19: 电话簿
//        if (StringUtils.isNotEmpty(abs)) {
//            addressBookList = JSONArray.parseArray(abs, AddressBook.class);
//        } else {
        addressBookList = spm.addressBookList(new AddressBook(queryId));

        for (AddressBook ad : addressBookList) {
            List<Phone> phones = JSONArray.parseArray(ad.getPhones_(), Phone.class);
            ad.setPhones(phones);
            ad.setPhones_("");
        }
//            redisCache.setCacheObject("AB::" + queryId, JSONArray.toJSONString(addressBookList), 2, TimeUnit.DAYS);
//        }
        return addressBookList;
    }

    public String getTelByName(Integer queryId, String name) {
        List<AddressBook> addressBookList = this.getAddressBook(queryId);
        for (AddressBook ad : addressBookList) {
            for (Phone phone : ad.getPhones()) {
                if (name.equals(phone.getLabel())) {
                    return phone.getValue();
                }
            }
        }
        return "";
    }

    @Override
    public List<CallLogResult> disCallLog(List<CallLog> list, CallLog callLog) {
        List<CallLogResult> callLogResults = new ArrayList<>();
        List<CallLogResult> finalCallLogResults = callLogResults;
        list.stream().forEach(new Consumer<CallLog>() {
            @Override
            public void accept(CallLog callLog) {
                String number = callLog.getNumber();
                int exist = -1;
                for (int i = 0; i < finalCallLogResults.size(); i++) {
                    if (number.equals(finalCallLogResults.get(i).getNumber())) {
                        exist = i;
                        break;
                    }
                }
                CallLogResult callLogResul;
                if (exist == -1) {
                    // 没有新创建
                    callLogResul = new CallLogResult(number);
                } else {
                    // 已有原地改
                    callLogResul = finalCallLogResults.get(exist);
                }
                // 联合处理
                if ("outgoing".equals(callLog.getCallType()) || "rejected".equals(callLog.getCallType())) {   //打出去
                    callLogResul.getCallNum().setZj(callLogResul.getCallNum().getZj() + 1);
                    callLogResul.getTotalCallDuration().setZj(callLogResul.getTotalCallDuration().getZj() + callLog.getDuration());
                } else {      //打进来
                    callLogResul.getCallNum().setBj(callLogResul.getCallNum().getBj() + 1);
                    callLogResul.getTotalCallDuration().setBj(callLogResul.getTotalCallDuration().getBj() + callLog.getDuration());
                }
                if (callLog.getTimestamp() > callLogResul.getRecentlyCallTime()) {
                    callLogResul.setRecentlyCallTime(callLog.getTimestamp());
                }
                // 已有 则编辑立即生效
                if (exist == -1) {// 没有 添加新创建
                    finalCallLogResults.add(callLogResul);
                }
            }
        });
        callLogResults = callLogResults.stream().sorted((x, y) -> y.getCallNum().getZj() - x.getCallNum().getZj()
        ).collect(Collectors.toList());

        List<AddressBook> addressBookList = getAddressBook(callLog.getQueryId());

        if (addressBookList != null && !addressBookList.isEmpty()) {
            for (CallLogResult ab : callLogResults) {
                ab.getNumber().replace(" ", "").replace("-", "").replace("+", "");

                ab.setName(getTelName(addressBookList, ab.getNumber()));
            }
        }
        return callLogResults;
    }

    @Override
    public List<TextMessage> disTextMessage(List<TextMessage> list, TextMessage textMessage) {
        List<AddressBook> addressBookList = getAddressBook(textMessage.getQueryId());
        for (TextMessage ab : list) {
            ab.setAddress(ab.getAddress().replace(" ", "").replace("-", "").replace("+", ""));
            ab.setName(getTelName(addressBookList, ab.getAddress()));
        }
        return list;
    }

    @Override
    public List<Contacts> disContacts(List<CallLogResult> callLogResults, JSONArray lxr) {
        List<Contacts> cons = new ArrayList<>();

        for (int i = 0; i < lxr.size(); i++) {
            JSONObject lxrJs = lxr.getJSONObject(i);
            Contacts contacts = new Contacts(lxrJs.getString("gx"), lxrJs.getString("xm"));
            for (CallLogResult callLogResult : callLogResults) {
                if (callLogResult.getNumber().equals(lxrJs.getString("lxfs"))) {
                    contacts.setName(callLogResult.getName());
                    contacts.setNumber(callLogResult.getNumber());
                    contacts.setCallNum(callLogResult.getCallNum());
                    contacts.setTotalCallDuration(callLogResult.getTotalCallDuration());
                    contacts.setRecentlyCallTime(callLogResult.getRecentlyCallTime());
                }
            }
            contacts.setNumber(lxrJs.getString("lxfs"));
            cons.add(contacts);
        }
        return cons;
    }
}
